/**
 * *** Service implementation ***
 * --test--
 */


package at.ticker.ebelticker;

import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;


// TODO Decision: Service vs IntentService
public class EBEL_TickerService extends Service {

    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();
    // Random number generator
    private final Random mGenerator = new Random();
	
	private static final String TAG = "EBEL_TickerService";
	private static final int HELLO_ID = 1;

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        EBEL_TickerService getService() {
            // Return this instance of LocalService so clients can call public methods
            return EBEL_TickerService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
    	Log.d(TAG, "onBind");
    	return mBinder;
    }

    
	/**
	 * The IntentService calls this method from the default worker thread with
	 * the intent that started the service. When this method returns, IntentService
	 * stops the service, as appropriate.
	 */
/*	@Override
	protected void onHandleIntent(Intent intent) {
		// Normally we would do some work here, like download a file.
		// For our sample, we just sleep for 5 seconds.
		long endTime = System.currentTimeMillis() + 5*1000;
		
		//Toast.makeText(this, "EBEL DoWork Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onHandleIntent-start");
		
		while (System.currentTimeMillis() < endTime) {
			synchronized (this) {
				try {
					wait(endTime - System.currentTimeMillis());
				} catch (Exception e) {
				}
			}
		}
		
        sendNotification();
		
		//Toast.makeText(this, "EBEL DoWork Ended", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onHandleIntent-end");
		
	}
*/

/*	
	@Override
	public void onCreate() {
		Toast.makeText(this, "EBEL Service Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
		
		//player = MediaPlayer.create(this, R.raw.braincandy);
		//player.setLooping(false); // Set looping
	}

*/

	@Override
	public void onDestroy() {
		Toast.makeText(this, "EBEL Service Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Toast.makeText(this, "EBEL Service Started", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onStart");
		return super.onStartCommand(intent, flags, startId);
	}

    public void sendNotification() {
		// Status Bar Notifications
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
		
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "Hello";
		long when = System.currentTimeMillis();
		
		Context context = getApplicationContext();
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this, EBEL_TickerService.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		Notification notification = new Notification(icon, tickerText, when);
		notification.defaults |= Notification.DEFAULT_SOUND;
		//notification.defaults |= Notification.DEFAULT_VIBRATE;
		//  ==> erzeugt eine securityException "Requires VIBRATE permissions"
		notification.defaults |= Notification.DEFAULT_LIGHTS;
		notification.flags    |= Notification.FLAG_AUTO_CANCEL;
		
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

		mNotificationManager.notify(HELLO_ID, notification);
		
		// Das gleiche notification Object kann aktualisiert werden....
		long endTime = System.currentTimeMillis() + 5*1000;
		while (System.currentTimeMillis() < endTime) {
			synchronized (this) {
				try {
					wait(endTime - System.currentTimeMillis());
				} catch (Exception e) {
				}
			}
		}
		notification.setLatestEventInfo(context, "Update", "Update!", contentIntent);
		mNotificationManager.notify(HELLO_ID, notification);
    }
	
	// Example of reading Android system information (battery status) via 
	// sticky broadcast intents
	public void readBatteryStatus() {
		// Register for the battery changed event
		IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

		// Intent is sticky so using null as receiver works fine
		// return value contains the status
		Intent batteryStatus = this.registerReceiver(null, filter);

		// Are we charging / charged?
		int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
		boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
			|| status == BatteryManager.BATTERY_STATUS_FULL;

		boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;

		// How are we charging?
		int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
		boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
		boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
	}
	
    /** method for clients */
    public int getRandomNumber() {
      return mGenerator.nextInt(100);
    }

    /** method for clients */
    public String getETAction() {
        ETAction action = new ETAction();
        return action.getAction();
    }
    
    /** method for clients */
    public ETAction getETActionObject() {
        ETAction action = new ETAction();
        return action;
    }    
    
}
